const basiCode = require('../util/baseCode.js');
const dateFormat = require('dateformat');
// 用户表
const userModel = require('../model/userModel.js');


/*
**name:新增用户
* mixnick： mixnick
**
*/
exports.addUser = async (params, cloud) => {
    console.log('-------------params-------------', params)
    //查询用户
    let getUser = await userModel.getUser(params.mixnick, cloud);
    if (getUser.length == 0) {
        let user = await userModel.addUser(params, cloud);
        if (user.insertId) {
            return { isOk: 1, msg: '新增成功', data: { user_id: user.insertId } };
        } else {
            return { isOk: 0, msg: '新增失败' };
        }
    } else {
        return { isOk: 1, msg: '用户已存在', data: getUser[0] };
    }
};

/*
**name:新增用户
* mixnick： mixnick
**
*/
exports.addCart = async (params, cloud) => {
    //查询用户 
    console.log("------------addCart---------------", params)
    let getUser = await userModel.getUser(params.mixnick, cloud);
    if (getUser.length) {
        let cart = await userModel.addCart(params, cloud);
        if (cart.insertId) {
            return await basiCode(0, { isOk: 1, msg: '加购成功' });
        } else {
            return await basiCode(0, { isOk: 0, msg: '加购失败' });
        }
    } else {
        return await basiCode(0, { isOk: 1, msg: '用户不存在' });
    }

};



//埋点数据
exports.addUserStat = async (params, cloud) => {
    console.log("==============service==================")
    let reduceNum = await userModel.addUserStat(params, dateFormat(new Date(), "yyyy-mm-dd hh:MM:ss"), cloud);
    if (reduceNum.affectedRows) {
        return await basiCode(0, { isOk: 1, msg: '添加成功' });
    }
};

function TralatetTime() {
    let TralatetTime = new Date().getTime() + 28800000;
    // let TralatetTime = new Date('2020-05-01 14:00:00').getTime();
    return TralatetTime;
}


/**
 * 查询订单
 * @param {nickName: string} 明文nick
 * @param {session: string} 
 */
getOrderList= async(props, cloud)=> {
    const {gmt_create,openId="" } =props 
    try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.open.trades.sold.get',
            // autoSession: "true",
            data: {
                'fields':'tid,orders',
                'start_created':  '2021-01-08 23:00:00', 
                // 'end_created': '2021-01-08 23:00:00', 
                'buyer_open_id': openId,
                session:"6100713781914eed3dbe31ca9bde1abefb31d0e1a2413601928865133",
            }               
        });
        return  result.trades.trade
    } catch (err) {
        return [];
    }
};



/**
 * 查询订单
 * @param {nickName: string} 明文nick
 * @param {session: string} 
 */
getOrderItem = async (props, cloud) => {

    const { tid } =props 
    try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.open.trade.get',
            // autoSession: "true",
            data: {
                'fields':'seller_memo',
                'tid': "1493924474650518566",
                session:"6100713781914eed3dbe31ca9bde1abefb31d0e1a2413601928865133",
            }               
        });
        return result.trade.seller_memo 
    } catch (err) {
        return " "
    }
};


/**
 * 查询订单
 * @param {nickName: string} 明文nick
 * @param {session: string} 
 */
setOrder = async (props, cloud) => {
    const {tid="",seller_memo="6666666",openId ,sample_data} =props 
    try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.trade.memo.update',
            autoSession: true,
            data: {
               'tid': tid,
                'memo': seller_memo+sample_data,
                'flag':'1',
                'buyer_open_id': openId
            }
        });
        console.log("11111111111111111111111111111111111",result)
        return true
    } catch (err) {
        return false
    }
};


/**
 * 订单匹配
 * @param {nickName: string} 明文nick
 * @param {session: string} 
 */
exports.matchOrder = async (props, cloud) => {
    const { date } =props 
    try {
        let catList = await userModel.matchOrder(date, cloud);
        if(catList.length == 0 ) return;
        for(let i = 0 ; i< catList.length;i++ ) {
              let catItem = catList[i]
              let  orderLsist = await getOrderList(catItem,cloud)
              if(orderLsist.length) {
                for(let j=0;j<orderLsist.length;j++) {
                  let orderItem = orderLsist[j];
                  //  catItem 和 orderItem 匹配
                  





                  if(true) {
                     //拿备注
                     let seller_memo = await getOrderItem(orderItem,cloud)
                     //改备注
                     let isOk = await setOrder({seller_memo, ...catItem},cloud)

                     //该数据
                      if(isOk) {

                      }
                  }
                }
              }
            
        }
    } catch (err) {
        return { isOk: 0, msg: err };
    }
};